package com.ruoyi.merchant.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.merchant.domain.*;
import com.ruoyi.merchant.mapper.ChatRecordMapper;
import com.ruoyi.merchant.mapper.MerchantNotificationSettingsMapper;
import com.ruoyi.merchant.mapper.OrdersMapper;
import com.ruoyi.merchant.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

/**
 * 消息服务实现
 */
@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private MerchantNotificationSettingsMapper notificationSettingsMapper;

    // 创建 ObjectMapper 实例用于 JSON 处理
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public MessageStatistics getMessageStatistics(Long merchantId) {
        MessageStatistics statistics = new MessageStatistics();

        // 1. 获取未读消息统计
        MessageStatistics.UnreadCount unreadCount = getUnreadCount(merchantId);
        statistics.setUnreadCount(unreadCount);

        // 2. 获取服务评分（基于chat_records表的service_rating字段）
        MessageStatistics.ServiceScore serviceScore = getServiceScore(merchantId);
        statistics.setServiceScore(serviceScore);

        return statistics;
    }

    /**
     * 获取未读消息统计
     */
    private MessageStatistics.UnreadCount getUnreadCount(Long merchantId) {
        MessageStatistics.UnreadCount unreadCount = new MessageStatistics.UnreadCount();

        try {
            // 从数据库查询未读消息统计
            Map<Integer, Map<String, Object>> unreadMap = chatRecordMapper.selectUnreadCountByMerchantId(merchantId);

            int total = 0;
            int customer = 0;
            int platform = 0;
            int group = 0;

            if (unreadMap != null && !unreadMap.isEmpty()) {
                for (Map.Entry<Integer, Map<String, Object>> entry : unreadMap.entrySet()) {
                    Integer chatType = entry.getKey();
                    Map<String, Object> countMap = entry.getValue();
                    Integer count = countMap != null && countMap.get("count") != null ?
                            ((Number) countMap.get("count")).intValue() : 0;

                    total += count;

                    // 根据chat_type分类
                    switch (chatType) {
                        case 1: // 用户与平台客服
                            platform = count;
                            break;
                        case 2: // 用户与商家
                            customer = count;
                            break;
                        case 3: // 系统通知
                            group = count;
                            break;
                        default:
                            // 其他类型计入总数但不单独分类
                            break;
                    }
                }
            }

            unreadCount.setTotal(total);
            unreadCount.setCustomer(customer);
            unreadCount.setPlatform(platform);
            unreadCount.setGroup(group);

        } catch (Exception e) {
            // 如果查询失败，设置默认值
            unreadCount.setTotal(0);
            unreadCount.setCustomer(0);
            unreadCount.setPlatform(0);
            unreadCount.setGroup(0);
            // 记录日志
            System.err.println("获取未读消息统计失败: " + e.getMessage());
        }

        return unreadCount;
    }

    /**
     * 获取服务评分（基于chat_records表的service_rating字段）
     */
    private MessageStatistics.ServiceScore getServiceScore(Long merchantId) {
        MessageStatistics.ServiceScore serviceScore = new MessageStatistics.ServiceScore();

        try {
            // 获取最近7天的服务评分
            Map<String, Object> currentScoreMap = chatRecordMapper.selectServiceScoreByMerchantId(merchantId, 7);
            // 获取前一个7天的服务评分（8-14天前，用于趋势计算）
            Map<String, Object> previousScoreMap = chatRecordMapper.selectPreviousServiceScore(merchantId, 7, 14);

            // 调试日志：打印查询结果
            System.out.println("当前周期评分统计: " + currentScoreMap);
            System.out.println("前一周期评分统计: " + previousScoreMap);

            double currentAvgScore = 0.0;
            int currentReviewCount = 0;

            if (currentScoreMap != null) {
                currentAvgScore = currentScoreMap.get("avg_score") != null ?
                        ((Number) currentScoreMap.get("avg_score")).doubleValue() : 0.0;
                currentReviewCount = currentScoreMap.get("review_count") != null ?
                        ((Number) currentScoreMap.get("review_count")).intValue() : 0;

                // 调试日志
                System.out.println("当前周期平均分: " + currentAvgScore + ", 评价数量: " + currentReviewCount);
            }

            double previousAvgScore = 0.0;
            int previousReviewCount = 0;

            if (previousScoreMap != null) {
                previousAvgScore = previousScoreMap.get("avg_score") != null ?
                        ((Number) previousScoreMap.get("avg_score")).doubleValue() : 0.0;
                previousReviewCount = previousScoreMap.get("review_count") != null ?
                        ((Number) previousScoreMap.get("review_count")).intValue() : 0;

                // 调试日志
                System.out.println("前一周期平均分: " + previousAvgScore + ", 评价数量: " + previousReviewCount);
            }

            // 直接使用5分制的平均分，保留1位小数
            Double score;
            if (currentReviewCount > 0) {
                // 保留1位小数
                score = Math.round(currentAvgScore * 10.0) / 10.0;
                System.out.println("5分制平均分数: " + score);
            } else {
                // 如果没有评分数据，使用默认高分（假设服务良好）
                score = 4.5; // 5分制的4.5分
                System.out.println("无评分数据，使用默认分数: " + score);
            }

            // 计算趋势
            String trend = calculateTrend(currentAvgScore, previousAvgScore, currentReviewCount, previousReviewCount);
            System.out.println("趋势计算结果: " + trend);

            // 设置统计周期
            String period = "近7日";

            serviceScore.setScore(score);
            serviceScore.setPeriod(period);
            serviceScore.setTrend(trend);

        } catch (Exception e) {
            // 如果查询失败，设置默认值
            serviceScore.setScore(4.5);
            serviceScore.setPeriod("近7日");
            serviceScore.setTrend("stable");
            // 记录日志
            System.err.println("获取服务评分失败: " + e.getMessage());
            e.printStackTrace();
        }

        return serviceScore;
    }

    /**
     * 计算评分趋势
     */
    private String calculateTrend(double currentScore, double previousScore,
                                  int currentReviewCount, int previousReviewCount) {
        // 如果当前周期没有评分数据，显示稳定
        if (currentReviewCount == 0) {
            return "stable";
        }

        // 如果前一个周期没有评分数据，无法比较趋势，显示稳定
        if (previousReviewCount == 0) {
            return "stable";
        }

        double diff = currentScore - previousScore;

        // 设置趋势判断阈值（5分制的0.1分差异）
        double threshold = 0.1;

        System.out.println("趋势计算 - 当前分: " + currentScore + ", 前一分: " + previousScore + ", 差异: " + diff);

        if (diff > threshold) {
            return "up";
        } else if (diff < -threshold) {
            return "down";
        } else {
            return "stable";
        }
    }

    /**
     * 安全获取整数值
     */
    private int getIntValue(Object value) {
        if (value == null) {
            return 0;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    @Override
    public List<MessageSession> getMessageSessions(Long merchantId, String msgType, Integer pageNum, Integer pageSize) {
        // 分页处理
        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;
        int offset = (pageNum - 1) * pageSize;

        // 获取会话列表
        List<Map<String, Object>> sessionMaps = chatRecordMapper.selectSessionListByMerchantId(merchantId, msgType);
        List<MessageSession> sessions = new ArrayList<>();

        for (Map<String, Object> map : sessionMaps) {
            // 修复类型转换问题
            Long sessionId = map.get("session_id") != null ?
                    ((Number) map.get("session_id")).longValue() : null;
            Integer chatType = map.get("chat_type") != null ?
                    ((Number) map.get("chat_type")).intValue() : null;
            Long userId = map.get("customer_id") != null ?  // 注意：这里存储的已经是 user_id
                    ((Number) map.get("customer_id")).longValue() : null;

            MessageSession session = new MessageSession();
            session.setSessionId(sessionId);
            session.setMsgType(convertChatTypeToMsgType(chatType));
            session.setUnreadCount(chatRecordMapper.selectUnreadCountBySessionId(sessionId, merchantId));

            // 设置最后一条消息
            ChatRecord lastMessage = chatRecordMapper.selectLastMessageBySessionId(sessionId);
            if (lastMessage != null) {
                MessageSession.LastMessage lastMsg = new MessageSession.LastMessage();
                lastMsg.setContent(lastMessage.getContent());
                lastMsg.setSentAt(lastMessage.getSentAt());
                lastMsg.setIsRead(lastMessage.getIsRead() == 1);
                lastMsg.setSenderType(convertSenderType(lastMessage.getSenderType()));
                session.setLastMessage(lastMsg);
            }

            // 根据聊天类型设置用户信息或发送者信息
            if (chatType != null && chatType == 2) { // 顾客消息
                // 使用 userId（即 users 表的 user_id）查询用户信息
                Map<String, Object> userInfoMap = chatRecordMapper.selectUserInfoByUserId(userId);
                MessageSession.UserInfo userInfo = new MessageSession.UserInfo();

                if (userInfoMap != null) {
                    // 使用查询到的 user_id 作为显示的用户ID
                    Long displayUserId = userInfoMap.get("userId") != null ?
                            ((Number) userInfoMap.get("userId")).longValue() : userId;
                    userInfo.setUserId(displayUserId);
                    userInfo.setUserName((String) userInfoMap.get("userName"));
                    String phone = (String) userInfoMap.get("phone");
                    if (phone != null && phone.length() >= 4) {
                        userInfo.setPhoneSuffix(phone.substring(phone.length() - 4));
                    }
                    // 使用实时头像
                    String avatar = processAvatarUrl((String) userInfoMap.get("avatar"), "/avatar/default-user.jpg");
                    userInfo.setAvatar(avatar);
                    System.out.println("DEBUG - 用户ID: " + displayUserId + ", 头像URL: " + avatar);
                } else {
                    // 如果查询不到用户信息，使用默认值
                    userInfo.setUserId(userId);
                    userInfo.setUserName("用户" + userId);
                    userInfo.setPhoneSuffix("****");
                    userInfo.setAvatar("/avatar/default-user.jpg");
                    System.out.println("DEBUG - 使用默认头像，userId: " + userId);
                }
                userInfo.setIsOnline(false);
                session.setUserInfo(userInfo);
            } else if (chatType != null && (chatType == 1 || chatType == 3)) { // 平台消息或群消息
                MessageSession.SenderInfo senderInfo = new MessageSession.SenderInfo();
                senderInfo.setSenderId(1L);
                senderInfo.setSenderName(chatType == 1 ? "平台客服" : "群聊");
                senderInfo.setAvatar("/avatar/platform.jpg");
                session.setSenderInfo(senderInfo);
            }

            sessions.add(session);
        }

        // 简单分页
        int end = Math.min(offset + pageSize, sessions.size());
        if (offset > sessions.size()) {
            return new ArrayList<>();
        }
        return sessions.subList(offset, end);
    }

    @Override
    public List<Map<String, Object>> getChatHistory(Long sessionId, Long merchantId, Integer pageNum, Integer pageSize) {
        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 20;

        List<ChatRecord> records = chatRecordMapper.selectChatHistoryBySessionId(sessionId, merchantId);
        List<Map<String, Object>> result = new ArrayList<>();

        // 预加载用户和商家信息，避免重复查询
        Map<Long, Map<String, Object>> userInfoCache = new HashMap<>();
        Map<Long, Map<String, Object>> merchantInfoCache = new HashMap<>();

        for (ChatRecord record : records) {
            Map<String, Object> message = new HashMap<>();
            message.put("messageId", record.getChatId());
            message.put("senderType", convertSenderType(record.getSenderType()));
            message.put("senderId", record.getSenderId());
            message.put("content", record.getContent());
            message.put("messageType", convertMessageType(record.getMessageType()));
            message.put("sentAt", record.getSentAt());
            message.put("isRead", record.getIsRead() == 1);

            // 添加头像信息
            addAvatarInfo(message, record, userInfoCache, merchantInfoCache);

            // 如果是优惠券消息，设置优惠券信息
            if (record.getMessageType() == 5 && record.getAttachments() != null) {
                try {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> couponInfo = objectMapper.readValue(record.getAttachments(), Map.class);
                    message.put("couponInfo", couponInfo);
                } catch (IOException e) {
                    // JSON 解析失败，不设置优惠券信息
                    System.err.println("Failed to parse attachments JSON: " + e.getMessage());
                }
            }

            // 快捷回复列表（可根据业务逻辑配置）
            if (record.getSenderType() == 1) { // 用户发送的消息
                List<String> quickReplies = Arrays.asList("好的", "谢谢", "我再看看");
                message.put("quickReplies", quickReplies);
            }

            result.add(message);
        }

        // 分页处理
        int offset = (pageNum - 1) * pageSize;
        int end = Math.min(offset + pageSize, result.size());
        if (offset > result.size()) {
            return new ArrayList<>();
        }
        return result.subList(offset, end);
    }

    /**
     * 添加头像信息
     */
    private void addAvatarInfo(Map<String, Object> message, ChatRecord record,
                               Map<Long, Map<String, Object>> userInfoCache,
                               Map<Long, Map<String, Object>> merchantInfoCache) {

        String senderType = convertSenderType(record.getSenderType());
        Long senderId = record.getSenderId();

        switch (senderType) {
            case "user":
                // 用户头像处理 - 使用 customer_id（现在存储的是 user_id）查询用户信息
                Long userId = record.getCustomerId(); // 这里存储的是 user_id

                Map<String, Object> userInfo = userInfoCache.get(userId);
                if (userInfo == null) {
                    userInfo = chatRecordMapper.selectUserInfoByUserId(userId);
                    if (userInfo != null) {
                        userInfoCache.put(userId, userInfo);
                    }
                }

                if (userInfo != null) {
                    String userAvatar = processAvatarUrl((String) userInfo.get("avatar"), "/avatar/default-user.jpg");
                    message.put("avatar", userAvatar);
                    message.put("userName", userInfo.get("userName"));
                    String phone = (String) userInfo.get("phone");
                    if (phone != null && phone.length() >= 4) {
                        message.put("phoneSuffix", phone.substring(phone.length() - 4));
                    }
                    System.out.println("DEBUG - 聊天记录用户ID: " + userId + ", 头像URL: " + userAvatar);
                } else {
                    message.put("avatar", "/avatar/default-user.jpg");
                    message.put("userName", "用户" + userId);
                    System.out.println("DEBUG - 聊天记录使用默认头像，userId: " + userId);
                }
                break;

            case "merchant":
                // 商家头像处理保持不变
                Map<String, Object> merchantInfo = merchantInfoCache.get(senderId);
                if (merchantInfo == null) {
                    merchantInfo = chatRecordMapper.selectMerchantInfoByUserId(senderId);
                    if (merchantInfo != null) {
                        merchantInfoCache.put(senderId, merchantInfo);
                    }
                }

                if (merchantInfo != null) {
                    String merchantAvatar = processAvatarUrl((String) merchantInfo.get("avatar"), "/avatar/default-merchant.jpg");
                    message.put("avatar", merchantAvatar);
                    message.put("merchantName", merchantInfo.get("merchantName") != null ?
                            merchantInfo.get("merchantName") : "商家" + senderId);
                } else {
                    message.put("avatar", "/avatar/default-merchant.jpg");
                    message.put("merchantName", "商家" + senderId);
                }
                break;

            case "system":
                message.put("avatar", processAvatarUrl(null, "/avatar/system.jpg"));
                message.put("senderName", "系统通知");
                break;

            default:
                message.put("avatar", "/avatar/default.jpg");
                break;
        }
    }

    /**
     * 处理头像URL
     */
    private String processAvatarUrl(String avatarUrl, String defaultAvatar) {
        if (avatarUrl == null || avatarUrl.trim().isEmpty()) {
            return defaultAvatar;
        }

        // 如果已经是完整URL，直接返回
        if (avatarUrl.startsWith("http://") || avatarUrl.startsWith("https://")) {
            return avatarUrl;
        }

        String baseUrl = getAvatarBaseUrl();

        // 处理相对路径
        if (avatarUrl.startsWith("/")) {
            return baseUrl + avatarUrl;
        } else {
            return baseUrl + "/" + avatarUrl;
        }
    }

    /**
     * 获取头像基础URL
     */
    private String getAvatarBaseUrl() {
        return "https://waimai-platform.oss-cn-hangzhou.aliyuncs.com";
    }

    @Override
    @Transactional
    public int sendMessage(Long sessionId, Long merchantId, Long customerId, String content,
                           String messageType, Map<String, Object> attachments) {
        // 如果 customerId 为 null 或 0，尝试从数据库查询
        if (customerId == null || customerId == 0) {
            customerId = getCustomerIdBySession(sessionId);
        }

        // 验证 customerId
        if (customerId == null || customerId == 0) {
            throw new RuntimeException("无法确定用户ID，会话ID: " + sessionId);
        }

        // 验证用户是否存在
        Map<String, Object> userInfo = chatRecordMapper.selectUserInfoByUserId(customerId);
        if (userInfo == null) {
            throw new RuntimeException("用户不存在，用户ID: " + customerId);
        }

        ChatRecord record = new ChatRecord();
        record.setSessionId(sessionId);
        record.setChatType(2); // 默认顾客消息
        record.setCustomerId(customerId);
        record.setMerchantId(merchantId);
        record.setSenderType(3); // 商家发送
        record.setSenderId(merchantId);
        record.setContent(content);
        record.setMessageType(convertMessageType(messageType));
        record.setSentAt(new Date());
        record.setIsRead(1); // 自己发送的消息默认已读

        // 处理附件
        if (attachments != null && !attachments.isEmpty()) {
            try {
                String attachmentsJson = objectMapper.writeValueAsString(attachments);
                record.setAttachments(attachmentsJson);
                System.out.println("DEBUG - 附件JSON: " + attachmentsJson);
            } catch (JsonProcessingException e) {
                System.err.println("附件序列化失败: " + e.getMessage());
            }
        }

        return chatRecordMapper.insertChatRecord(record);
    }

    @Override
    @Transactional
    public int sendMessage(Long sessionId, Long merchantId, Long customerId, String content, String messageType) {
        // 调用带附件的方法，附件为null
        return sendMessage(sessionId, merchantId, customerId, content, messageType, null);
    }

    @Override
    @Transactional
    public int sendCoupon(Long sessionId, Long merchantId, Long customerId, Long couponTemplateId, String customMessage) {
        // customerId 应该已经是 users 表的 user_id
        if (customerId == null || customerId == 0) {
            customerId = getCustomerIdBySession(sessionId);
        }

        // 验证 customerId
        if (customerId == null || customerId == 0) {
            throw new RuntimeException("无法确定用户ID，会话ID: " + sessionId);
        }

        // 验证用户是否存在
        Map<String, Object> userInfo = chatRecordMapper.selectUserInfoByUserId(customerId);
        if (userInfo == null) {
            throw new RuntimeException("用户不存在，用户ID: " + customerId);
        }

        // 1. 校验优惠券模板是否存在且可用
        // 2. 发送优惠券消息
        ChatRecord record = new ChatRecord();
        record.setSessionId(sessionId);
        record.setChatType(2); // 顾客消息
        record.setCustomerId(customerId);
        record.setMerchantId(merchantId);
        record.setSenderType(3); // 商家发送
        record.setSenderId(merchantId);
        record.setContent(customMessage != null ? customMessage : "给您发送了一张优惠券");
        record.setMessageType(5); // 优惠券类型
        record.setSentAt(new Date());
        record.setIsRead(1);

        // 在attachments中存储优惠券信息
        Map<String, Object> attachments = new HashMap<>();
        attachments.put("couponTemplateId", couponTemplateId);
        // 这里需要从优惠券服务获取优惠券详情
        attachments.put("couponId", System.currentTimeMillis()); // 模拟优惠券ID
        attachments.put("title", "满100减10元优惠券");
        attachments.put("amount", 10);
        attachments.put("minOrderAmount", 100);
        attachments.put("expireAt", DateUtils.addDays(new Date(), 7));

        try {
            // 手动序列化为 JSON 字符串
            String attachmentsJson = objectMapper.writeValueAsString(attachments);
            record.setAttachments(attachmentsJson);
        } catch (JsonProcessingException e) {
            // 如果序列化失败，设置为空
            record.setAttachments(null);
            // 可以在这里记录日志
            System.err.println("Failed to serialize attachments to JSON: " + e.getMessage());
        }

        return chatRecordMapper.insertChatRecord(record);
    }

    @Override
    @Transactional
    public int markMessagesAsRead(Long sessionId, Long merchantId, List<Long> messageIds) {
        return chatRecordMapper.markMessagesAsRead(sessionId, messageIds, merchantId);
    }

    @Override
    public List<Map<String, Object>> getAvailableCoupons(Long merchantId) {
        // 这里需要调用优惠券服务，返回可用优惠券列表
        // 模拟数据
        List<Map<String, Object>> coupons = new ArrayList<>();

        Map<String, Object> coupon1 = new HashMap<>();
        coupon1.put("couponTemplateId", 1L);
        coupon1.put("name", "满100减10元");
        coupon1.put("description", "满100元使用");
        coupon1.put("type", 1);
        coupon1.put("discountValue", 10);
        coupon1.put("minOrderAmount", 100);
        coupon1.put("validDays", 7);
        coupon1.put("validTo", DateUtils.addDays(new Date(), 30));
        coupon1.put("stock", 100);
        coupon1.put("isActive", true);
        coupons.add(coupon1);

        Map<String, Object> coupon2 = new HashMap<>();
        coupon2.put("couponTemplateId", 2L);
        coupon2.put("name", "8.5折优惠券");
        coupon2.put("description", "最高优惠20元");
        coupon2.put("type", 2);
        coupon2.put("discountValue", 0.85);
        coupon2.put("maxDiscountAmount", 20);
        coupon2.put("minOrderAmount", 50);
        coupon2.put("validDays", 3);
        coupon2.put("validTo", DateUtils.addDays(new Date(), 7));
        coupon2.put("stock", 50);
        coupon2.put("isActive", true);
        coupons.add(coupon2);

        return coupons;
    }

    @Override
    @Transactional
    public int deleteMessageSession(Long sessionId, Long merchantId) {
        // 软删除该会话下的所有消息
        return chatRecordMapper.softDeleteMessagesBySessionId(sessionId, merchantId);
    }

    @Override
    public NotificationSettings getNotificationSettings(Long merchantId) {
        // 从数据库获取通知设置
        MerchantNotificationSettings dbSettings = notificationSettingsMapper.selectByMerchantId(merchantId);

        NotificationSettings settings = new NotificationSettings();

        if (dbSettings != null) {
            // 使用数据库中的设置
            settings.setEnableCustomerMessage(dbSettings.getEnableCustomerMessage());
            settings.setEnablePlatformMessage(dbSettings.getEnablePlatformMessage());
            settings.setEnableGroupMessage(dbSettings.getEnableGroupMessage());
            settings.setEnableSound(dbSettings.getEnableSound());
            settings.setEnableVibration(dbSettings.getEnableVibration());
            settings.setQuietHoursStart(dbSettings.getQuietHoursStart());
            settings.setQuietHoursEnd(dbSettings.getQuietHoursEnd());
        } else {
            // 如果没有找到设置，创建默认设置并保存到数据库
            settings.setEnableCustomerMessage(true);
            settings.setEnablePlatformMessage(true);
            settings.setEnableGroupMessage(true);
            settings.setEnableSound(true);
            settings.setEnableVibration(true);
            settings.setQuietHoursStart("22:00");
            settings.setQuietHoursEnd("08:00");

            // 保存默认设置到数据库
            MerchantNotificationSettings newSettings = new MerchantNotificationSettings();
            newSettings.setMerchantId(merchantId);
            newSettings.setEnableCustomerMessage(true);
            newSettings.setEnablePlatformMessage(true);
            newSettings.setEnableGroupMessage(true);
            newSettings.setEnableSound(true);
            newSettings.setEnableVibration(true);
            newSettings.setQuietHoursStart("22:00");
            newSettings.setQuietHoursEnd("08:00");

            notificationSettingsMapper.insert(newSettings);
        }

        return settings;
    }

    @Override
    @Transactional
    public int updateNotificationSettings(Long merchantId, NotificationSettings settings) {
        // 检查是否已存在设置
        MerchantNotificationSettings existingSettings = notificationSettingsMapper.selectByMerchantId(merchantId);

        MerchantNotificationSettings dbSettings = new MerchantNotificationSettings();
        dbSettings.setMerchantId(merchantId);
        dbSettings.setEnableCustomerMessage(settings.getEnableCustomerMessage());
        dbSettings.setEnablePlatformMessage(settings.getEnablePlatformMessage());
        dbSettings.setEnableGroupMessage(settings.getEnableGroupMessage());
        dbSettings.setEnableSound(settings.getEnableSound());
        dbSettings.setEnableVibration(settings.getEnableVibration());
        dbSettings.setQuietHoursStart(settings.getQuietHoursStart());
        dbSettings.setQuietHoursEnd(settings.getQuietHoursEnd());

        if (existingSettings != null) {
            // 更新现有设置
            return notificationSettingsMapper.updateByMerchantId(dbSettings);
        } else {
            // 插入新设置
            return notificationSettingsMapper.insert(dbSettings);
        }
    }

    /**
     * 查询会话对应的 customerId
     */
    private Long getCustomerIdBySession(Long sessionId) {
        return chatRecordMapper.selectCustomerIdBySession(sessionId);
    }

    /**
     * 将聊天类型转换为消息类型字符串
     */
    private String convertChatTypeToMsgType(Integer chatType) {
        switch (chatType) {
            case 1: return "platform";
            case 2: return "customer";
            case 3: return "group";
            default: return "customer";
        }
    }

    /**
     * 将发送者类型转换为字符串
     */
    private String convertSenderType(Integer senderType) {
        switch (senderType) {
            case 1: return "user";
            case 2: return "system";
            case 3: return "merchant";
            case 4: return "system";
            default: return "system";
        }
    }

    /**
     * 将消息类型字符串转换为数字
     */
    private Integer convertMessageType(String messageType) {
        if (messageType == null) return 1;
        switch (messageType) {
            case "text": return 1;
            case "image": return 2;
            case "file": return 3;
            case "voice": return 4;
            case "coupon": return 5;
            case "group_invite": return 6;
            default: return 1;
        }
    }

    /**
     * 将消息类型数字转换为字符串
     */
    private String convertMessageType(Integer messageType) {
        if (messageType == null) return "text";
        switch (messageType) {
            case 1: return "text";
            case 2: return "image";
            case 3: return "file";
            case 4: return "voice";
            case 5: return "coupon";
            case 6: return "group_invite";
            default: return "text";
        }
    }

    @Override
    public Map<String, Object> getLatestOrderBySessionId(Long sessionId, Long merchantId) {
        // 1. 根据会话ID获取用户ID
        Long customerId = getCustomerIdBySession(sessionId);
        if (customerId == null || customerId == 0) {
            throw new RuntimeException("无法获取用户信息");
        }

        // 2. 验证商家是否有权限访问此会话
        if (!chatRecordMapper.checkSessionAccess(sessionId, merchantId)) {
            throw new RuntimeException("无权限访问此会话");
        }

        // 3. 查询用户最新订单
        Orders latestOrder = ordersMapper.selectLatestOrderByCustomerIdAndMerchantId(customerId, merchantId);

        if (latestOrder == null) {
            throw new RuntimeException("该用户暂无订单");
        }

        // 4. 补充订单详细信息
        return enrichOrderDetails(latestOrder);
    }

    /**
     * 丰富订单详情信息 - 根据实际的 Orders 实体类字段调整
     */
    private Map<String, Object> enrichOrderDetails(Orders order) {
        if (order == null) return null;

        Map<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("orderId", order.getOrderId());
        orderDetail.put("orderNo", order.getOrderNo());
        orderDetail.put("customerId", order.getCustomerId());
        orderDetail.put("merchantId", order.getMerchantId());
        orderDetail.put("totalAmount", order.getTotalAmount());
        orderDetail.put("discountAmount", order.getDiscountAmount());
        orderDetail.put("regionSubsidy", order.getRegionSubsidy());
        orderDetail.put("finalAmount", order.getFinalAmount());
        orderDetail.put("orderStatus", order.getStatus());
        orderDetail.put("paymentStatus", order.getPaymentStatus());
        orderDetail.put("paymentMethod", order.getPaymentMethod());
        orderDetail.put("orderTime", order.getCreatedAt());
        orderDetail.put("paidAt", order.getPaidAt());
        orderDetail.put("finishedAt", order.getFinishedAt());
        orderDetail.put("canceledAt", order.getCanceledAt());
        orderDetail.put("pickupCode", order.getPickupCode());
        orderDetail.put("addressSnapshot", order.getAddressSnapshot());
        orderDetail.put("estimatedReadyMin", order.getEstimatedReadyMin());
        orderDetail.put("remark", order.getRemark());

        // 获取订单商品列表
        List<Map<String, Object>> orderItems = ordersMapper.selectOrderItemsByOrderId(order.getOrderId());

        // 处理 taste_options JSON 字段
        processTasteOptions(orderItems);

        orderDetail.put("orderItems", orderItems);

        // 从订单状态字段生成
        List<Map<String, Object>> orderTimeline = generateOrderTimeline(order);
        orderDetail.put("orderTimeline", orderTimeline);

        // 格式化金额显示
        if (order.getTotalAmount() != null) {
            orderDetail.put("totalAmountFormatted", String.format("¥%.2f", order.getTotalAmount()));
        }

        if (order.getFinalAmount() != null) {
            orderDetail.put("finalAmountFormatted", String.format("¥%.2f", order.getFinalAmount()));
        }

        if (order.getDiscountAmount() != null) {
            orderDetail.put("discountAmountFormatted", String.format("¥%.2f", order.getDiscountAmount()));
        }

        // 添加状态文本映射
        orderDetail.put("orderStatusText", getOrderStatusText(order.getStatus()));
        orderDetail.put("paymentStatusText", getPaymentStatusText(order.getPaymentStatus()));
        orderDetail.put("paymentMethodText", getPaymentMethodText(order.getPaymentMethod()));

        return orderDetail;
    }

    /**
     * 处理 taste_options JSON 字段，转换为 specifications 格式
     */
    private void processTasteOptions(List<Map<String, Object>> orderItems) {
        for (Map<String, Object> item : orderItems) {
            Object tasteOptions = item.get("tasteOptions");

            // 移除原始的 tasteOptions 字段
            item.remove("tasteOptions");

            // 解析 taste_options JSON 并转换为 specifications 格式
            String specifications = parseTasteOptions(tasteOptions);
            item.put("specifications", specifications);
        }
    }

    /**
     * 解析 taste_options JSON 字段
     */
    private String parseTasteOptions(Object tasteOptions) {
        if (tasteOptions == null) {
            return "";
        }

        try {
            // 如果 taste_options 已经是字符串格式的 JSON
            if (tasteOptions instanceof String) {
                String tasteOptionsStr = (String) tasteOptions;
                if (tasteOptionsStr.trim().isEmpty() || "null".equals(tasteOptionsStr)) {
                    return "";
                }

                // 使用 ObjectMapper 解析 JSON
                ObjectMapper mapper = new ObjectMapper();
                Object tasteObj = mapper.readValue(tasteOptionsStr, Object.class);
                return formatTasteOptions(tasteObj);
            }
            // 如果 taste_options 已经是解析后的对象（Map 或 List）
            else {
                return formatTasteOptions(tasteOptions);
            }
        } catch (Exception e) {
            // 解析失败，返回原始字符串或空值
            System.err.println("解析 taste_options 失败: " + e.getMessage());
            return tasteOptions.toString();
        }
    }

    /**
     * 格式化口味选项为字符串
     */
    private String formatTasteOptions(Object tasteObj) {
        if (tasteObj == null) {
            return "";
        }

        // 如果是 Map 类型（例如：{"辣度": "中辣", "温度": "热"}）
        if (tasteObj instanceof Map) {
            Map<?, ?> tasteMap = (Map<?, ?>) tasteObj;
            if (tasteMap.isEmpty()) {
                return "";
            }

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<?, ?> entry : tasteMap.entrySet()) {
                if (sb.length() > 0) {
                    sb.append("，");
                }
                sb.append(entry.getKey()).append(":").append(entry.getValue());
            }
            return sb.toString();
        }
        // 如果是 List 类型（例如：["中辣", "加冰"]）
        else if (tasteObj instanceof List) {
            List<?> tasteList = (List<?>) tasteObj;
            if (tasteList.isEmpty()) {
                return "";
            }

            StringBuilder sb = new StringBuilder();
            for (Object item : tasteList) {
                if (sb.length() > 0) {
                    sb.append("，");
                }
                sb.append(item);
            }
            return sb.toString();
        }
        // 其他类型直接转为字符串
        else {
            return tasteObj.toString();
        }
    }

    /**
     * 获取订单状态文本 - 根据 Long 类型状态值
     */
    private String getOrderStatusText(Long orderStatus) {
        if (orderStatus == null) return "未知状态";

        switch (orderStatus.intValue()) {
            case 1: return "待接单";
            case 2: return "已接单";
            case 3: return "制作中";
            case 4: return "待取餐";
            case 5: return "配送中";
            case 6: return "已完成";
            case 7: return "已取消";
            case 8: return "已退款";
            default: return "状态" + orderStatus;
        }
    }

    /**
     * 获取支付状态文本 - 根据 Long 类型状态值
     */
    private String getPaymentStatusText(Long paymentStatus) {
        if (paymentStatus == null) return "未知状态";

        switch (paymentStatus.intValue()) {
            case 1: return "待支付";
            case 2: return "已支付";
            case 3: return "已退款";
            case 4: return "支付失败";
            default: return "状态" + paymentStatus;
        }
    }

    /**
     * 获取支付方式文本 - 根据 Long 类型支付方式
     */
    private String getPaymentMethodText(Long paymentMethod) {
        if (paymentMethod == null) return "未知";

        switch (paymentMethod.intValue()) {
            case 1: return "微信支付";
            case 2: return "支付宝";
            case 3: return "现金";
            default: return "方式" + paymentMethod;
        }
    }

    /**
     * 根据订单信息生成订单时间线
     */
    private List<Map<String, Object>> generateOrderTimeline(Orders order) {
        List<Map<String, Object>> timeline = new ArrayList<>();

        // 下单时间
        if (order.getCreatedAt() != null) {
            Map<String, Object> createdEvent = new HashMap<>();
            createdEvent.put("status", "created");
            createdEvent.put("createTime", order.getCreatedAt());
            createdEvent.put("remark", "用户提交订单");
            createdEvent.put("operator", "系统");
            timeline.add(createdEvent);
        }

        // 支付时间
        if (order.getPaidAt() != null && order.getPaymentStatus() != null && order.getPaymentStatus().intValue() == 2) {
            Map<String, Object> paidEvent = new HashMap<>();
            paidEvent.put("status", "paid");
            paidEvent.put("createTime", order.getPaidAt());
            paidEvent.put("remark", "订单支付成功");
            paidEvent.put("operator", "系统");
            timeline.add(paidEvent);
        }

        // 根据订单状态添加相应的事件
        if (order.getStatus() != null) {
            Map<String, Object> statusEvent = new HashMap<>();
            statusEvent.put("status", getOrderStatusText(order.getStatus()).toLowerCase());
            statusEvent.put("createTime", getStatusTime(order));
            statusEvent.put("remark", getStatusRemark(order.getStatus()));
            statusEvent.put("operator", "商家");
            timeline.add(statusEvent);
        }

        // 完成时间
        if (order.getFinishedAt() != null && order.getStatus() != null && order.getStatus().intValue() == 6) {
            Map<String, Object> finishedEvent = new HashMap<>();
            finishedEvent.put("status", "completed");
            finishedEvent.put("createTime", order.getFinishedAt());
            finishedEvent.put("remark", "订单已完成");
            finishedEvent.put("operator", "系统");
            timeline.add(finishedEvent);
        }

        // 取消时间
        if (order.getCanceledAt() != null && order.getStatus() != null && order.getStatus().intValue() == 7) {
            Map<String, Object> canceledEvent = new HashMap<>();
            canceledEvent.put("status", "canceled");
            canceledEvent.put("createTime", order.getCanceledAt());
            canceledEvent.put("remark", "订单已取消");
            canceledEvent.put("operator", order.getCanceledAt().equals(order.getCreatedAt()) ? "用户" : "系统");
            timeline.add(canceledEvent);
        }

        // 按时间排序
        timeline.sort((a, b) -> {
            Date timeA = (Date) a.get("createTime");
            Date timeB = (Date) b.get("createTime");
            return timeA.compareTo(timeB);
        });

        return timeline;
    }

    /**
     * 根据订单状态获取相应的时间
     */
    private Date getStatusTime(Orders order) {
        if (order.getFinishedAt() != null && order.getStatus() != null && order.getStatus().intValue() == 6) {
            return order.getFinishedAt();
        } else if (order.getCanceledAt() != null && order.getStatus() != null && order.getStatus().intValue() == 7) {
            return order.getCanceledAt();
        } else if (order.getPaidAt() != null) {
            return order.getPaidAt();
        } else {
            return order.getCreatedAt();
        }
    }

    /**
     * 根据订单状态获取状态说明
     */
    private String getStatusRemark(Long status) {
        if (status == null) return "订单状态更新";

        switch (status.intValue()) {
            case 1: return "商家已接单";
            case 2: return "订单制作中";
            case 3: return "订单已打包";
            case 4: return "骑手已接单";
            case 5: return "订单配送中";
            case 6: return "订单已完成";
            case 7: return "订单已取消";
            case 8: return "订单已退款";
            default: return "订单状态更新";
        }
    }
}